package com.cci.kangdao.service.impl;

import com.cci.kangdao.azureAD.HttpClientHelper;
import com.cci.kangdao.service.AzureTokenService;
import com.cci.kangdao.service.PropertiesUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author William Du
 * @date 2019/4/28
 */
@Service
public class AzureTokenServiceImpl implements AzureTokenService {

    private Logger log = Logger.getLogger(this.getClass().getName());

    @Resource
    private PropertiesUtils propertiesUtils;

    @Override
    public String refreshToken(String userId) {
        try {
            StringBuffer sb = new StringBuffer(this.propertiesUtils.getPropertiesValue("common.security.refreshToken")).append("?userId=").append(userId);
            URL url = new URL(sb.toString());
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestProperty("Accept", "application/json;odata=minimalmetadata");
            conn.setRequestProperty("Content-Type", "application/json");
            String goodRespStr = HttpClientHelper.getResponseStringFromConn(conn, true);
            int responseCode = conn.getResponseCode();
            log.info("goodRespStr ->" + responseCode + "===>" + goodRespStr);
            if (responseCode == 200) {
                net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(goodRespStr);
                net.sf.json.JSONObject data = jsonObject.getJSONObject("data");
                if (null != data) {
                    return data.getString("token");
                }
                return null;
            } else {
                log.error("远程刷新token异常，响应：" + goodRespStr);
            }
        } catch (IOException e) {
            log.error(e.getMessage(),e);
        }
        return null;
    }
}
